package com.chiancloud.shield.server.services.curator;

import com.google.common.base.Preconditions;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.service.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;

/**
 * Created by wanghui on 14-8-20.
 */
public class CuratorService extends AbstractService {

    private static final Logger log =
            LoggerFactory.getLogger(CuratorService.class);
    protected final String basePath;

    private final CuratorFramework curator;
    private CuratorHelper curatorHelper;


    public CuratorService(String name,
                          CuratorFramework curator,
                          String basePath) {
        super(name);
        this.curator = Preconditions.checkNotNull(curator, "null curator");
        this.basePath = basePath;
    }


    @Override
    protected void serviceInit(Configuration conf) throws Exception {
        super.serviceInit(conf);
        curatorHelper = new CuratorHelper(conf, basePath);
    }

    @Override
    protected void serviceStart() throws Exception {
        curator.start();
        super.serviceStart();
    }

    @Override
    protected void serviceStop() throws Exception {
        super.serviceStop();
        closeCuratorComponent(curator);
    }

    public CuratorFramework getCurator() {
        return curator;
    }

    protected void closeCuratorComponent(Closeable closeable) {
        try {
            IOUtils.closeStream(closeable);
        } catch (Throwable ignored) {
            //triggered on an attempt to close before started
            log.debug("Error when closing {}", ignored);
        }
    }

    public String pathForServicetype(String servicetype) {
        return ZKPaths.makePath(getBasePath(), servicetype);
    }

    protected String pathForInstance(String servicetype, String id) {
        Preconditions.checkNotNull(servicetype);
        Preconditions.checkNotNull(id);
        return ZKPaths.makePath(pathForServicetype(servicetype), id);
    }

    public String getBasePath() {
        return basePath;
    }

    public CuratorHelper getCuratorHelper() {
        return curatorHelper;
    }
}
